package org.jeecg.modules.demo.mall.yxuser.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IpUtils;
import org.jeecg.modules.demo.mall.dto.WorkDto;
import org.jeecg.modules.demo.mall.entity.YxSystemUserLevel;
import org.jeecg.modules.demo.mall.entity.YxUser;
import org.jeecg.modules.demo.mall.yxstoreproduct.service.IYxStoreProductService;
import org.jeecg.modules.demo.mall.yxsystemuserlevel.service.IYxSystemUserLevelService;
import org.jeecg.modules.demo.mall.yxuser.service.IYxUserService;
import org.jeecg.modules.demo.mall.yxuserlevel.service.IYxUserLevelService;
import org.jeecg.modules.demo.weixin.api.WeixinHelloApi;
import org.jeecg.modules.demo.weixin.entity.SmtDev;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 会员表
 * @Author: jeecg-boot
 * @Date: 2023-10-24
 * @Version: V1.0
 */
@Api(tags = "yx_user")
@RestController
@RequestMapping("/mall/yxuser/yxUser")
@Slf4j
public class YxUserController extends JeecgController<YxUser, IYxUserService> {
    @Autowired
    private IYxUserService yxUserService;
    @Autowired
    private IYxStoreProductService storeProductService;

    @Autowired
    private IYxUserLevelService yxUserLevelService;
    @Autowired
    private IYxSystemUserLevelService yxSystemUserLevelService;
    @Resource
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private WeixinHelloApi weixinHelloApi;

    /**
     * 分页列表查询
     *
     * @param yxUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "yx_user-分页列表查询")
    @ApiOperation(value = "yx_user-分页列表查询", notes = "yx_user-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryUserByMerchantId(YxUser yxUser,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                           HttpServletRequest req) {
        QueryWrapper<YxUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("merchant_id", Integer.parseInt(yxUser.getMerId()));
        if (StringUtils.isNotBlank(yxUser.getNickname())) {
            queryWrapper.like("nickname", yxUser.getNickname());
        }
        if (StringUtils.isNotBlank(yxUser.getPhone())) {
            queryWrapper.like("phone", yxUser.getPhone());
        }
        queryWrapper.eq("status", 1);
        if (StringUtils.isNotBlank(yxUser.getRealName())) {
            queryWrapper.like("real_name", yxUser.getRealName());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<YxUser> page = new Page<>(pageNo, pageSize);
        IPage<YxUser> pageList = yxUserService.page(page, queryWrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())) {
            return Result.OK(pageList);
        }
        List<YxUser> yxUserList = pageList.getRecords().stream().map(item -> {
            YxSystemUserLevel yxSystemUserLevel = yxSystemUserLevelService.queryLevel(item.getUid(), item.getUserGrowthValue());
            if (yxSystemUserLevel != null) {
                item.setGrade(yxSystemUserLevel.getGrade());
                item.setLevelName(yxSystemUserLevel.getName());
                item.setDiscount(yxSystemUserLevel.getDiscount());
                item.setLevel(yxSystemUserLevel.getId());
                yxUserService.updateById(item);
            }
            return item;
        }).collect(Collectors.toList());
        return Result.OK(pageList.setRecords(yxUserList));
    }

    /**
     * 分页列表查询
     *
     * @param yxUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "yx_user-分页列表查询")
    @ApiOperation(value = "yx_user-分页列表查询", notes = "yx_user-分页列表查询")
    @GetMapping(value = "/queryList")
    public Result<?> queryList(YxUser yxUser,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                           HttpServletRequest req) {
        if (yxUser.getMerId() != null){
            yxUser.setMerchantId(Integer.valueOf(yxUser.getMerId()));
        }
        QueryWrapper<YxUser> queryWrapper = QueryGenerator.initQueryWrapper(yxUser, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<YxUser> page = new Page<YxUser>(pageNo, pageSize);
        IPage<YxUser> pageList = yxUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param yxUser
     * @return
     */
    @AutoLog(value = "yx_user-添加")
    @ApiOperation(value = "yx_user-添加", notes = "yx_user-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody YxUser yxUser, HttpServletRequest request) {
        yxUser.setLastIp(IpUtils.getIpAddr(request));
        yxUserService.save(yxUser);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param yxUser
     * @return
     */
    @AutoLog(value = "yx_user-编辑")
    @ApiOperation(value = "yx_user-编辑", notes = "yx_user-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody YxUser yxUser) {
        yxUserService.updateById(yxUser);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "yx_user-通过id删除")
    @ApiOperation(value = "yx_user-通过id删除", notes = "yx_user-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) Integer id) {
        yxUserService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "yx_user-批量删除")
    @ApiOperation(value = "yx_user-批量删除", notes = "yx_user-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.yxUserService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "yx_user-通过id查询")
    @ApiOperation(value = "yx_user-通过id查询", notes = "yx_user-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<YxUser> queryById(@RequestParam(name = "id", required = true) Integer id) {
        YxUser yxUser = yxUserService.getById(id);
        if (yxUser == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(yxUser);
    }

    /**
     * 通过id和门店查询
     *
     * @param id
     * @return
     */

    @ApiOperation(value = "yx_user-通过id和门店查询", notes = "yx_user-通过id和门店查询")
    @GetMapping(value = "/queryUser")
    public YxUser queryUser(@RequestParam Integer id) {
        LambdaQueryWrapper<YxUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(YxUser::getMerchantId, Integer.valueOf(merId));
        queryWrapper.eq(YxUser::getUid, id);
        YxUser yxUser = yxUserService.getOne(queryWrapper);
        if (yxUser == null) {
            return null;
        }
        return yxUser;
    }

    /**
     * 通过门店查询管理员（订单专用  没有状态查询  顶顶那根据商户进行返回  别删除  谨慎）
     *
     * @param merId
     * @return
     */

    @ApiOperation(value = "yx_user-通过门店查询管理员", notes = "yx_user-通过门店查询管理员")
    @GetMapping(value = "/queryUserList")
    public List<YxUser> queryUserList(@RequestParam(name = "merId", required = true) String merId) {
        LambdaQueryWrapper<YxUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YxUser::getMerchantId, Integer.valueOf(merId));
        queryWrapper.eq(YxUser::getUserType, "business");
        //防止用户被删除后订单信息查不到
//        queryWrapper.eq(YxUser::getStatus, 1);
        List<YxUser> yxUsers = yxUserService.list(queryWrapper);
        if (yxUsers == null) {
            return null;
        }
        return yxUsers;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param yxUser
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YxUser yxUser) {
        return super.exportXls(request, yxUser, YxUser.class, "yx_user");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YxUser.class);
    }

//    /**
//     * 用户充值时更新用户余额和积分
//     */
//    @PostMapping(value = "/updateAmount")
//    public void updateAmount(@RequestBody YxUser yxUser) {
//        YxUser user = yxUserService.getById(yxUser.getUid());
//        //计算余额和积分并更新
//        //判断订单类型不为null时为储值订单退款逻辑处理
//        if (yxUser.getOrderTypes() != null) {
//            user.setNowMoney(yxUser.getTotalPrice() == null ? user.getNowMoney() : user.getNowMoney().subtract(yxUser.getTotalPrice()));
//            user.setIntegral(yxUser.getIntegral() == null ? user.getIntegral() : user.getIntegral().subtract(yxUser.getIntegral()));
//        } else {
//            user.setIntegral(yxUser.getIntegral() == null ? user.getIntegral() : yxUser.getIntegral().add(user.getIntegral() == null ? BigDecimal.valueOf(0) : user.getIntegral()));
//            user.setNowMoney(yxUser.getTotalPrice() == null ? user.getNowMoney() : yxUser.getTotalPrice().add(user.getNowMoney()));
//        }
//        //退款时才有此值代表支付时余额支付的金额 退款时退回余额
//        if (yxUser.getRefundBalance() != null) {
//            user.setNowMoney(user.getNowMoney().add(yxUser.getRefundBalance()));
//        }
//        yxUserService.updateById(user);
//    }

    /**
     * 用户使用余额支付时扣掉余额
     */
    @PostMapping(value = "/subBalance")
    public Result<?> subBalance(@RequestBody YxUser yxUser) {
        YxUser user = yxUserService.getById(yxUser.getUid());
        if (yxUser.getNowMoney().compareTo(user.getNowMoney()) > 0) {
            return Result.error(606, "余额不足！");
        }
        //计算余额和积分并更新
        user.setNowMoney(user.getNowMoney().subtract(yxUser.getNowMoney()));
        yxUserService.updateById(user);
        return Result.OK("扣除余额成功！");
    }

    /**
     * 根据id更新绑定的商家
     */
    @PostMapping(value = "/updateMerchant")
    public Result<?> updateMerchant(@RequestBody YxUser yxUser) {
        yxUserService.updateById(yxUser);
        return Result.OK("更新商家id成功！");
    }

    /**
     * 查询小程序进来的商家用户
     */
    @GetMapping(value = "/queryMerchantUser")
    public Result<?> queryMerchantUser(@RequestParam(name = "current", defaultValue = "1") Integer current,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       String phone) {
        QueryWrapper<YxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_type", "business");
        queryWrapper.eq("status", 1);
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.like("phone", phone);
        }
        queryWrapper.isNull("merchant_id");
        IPage<YxUser> page = new Page<>(current, pageSize);
        IPage<YxUser> pageList = yxUserService.page(page, queryWrapper);
        pageList.getRecords().forEach(yxUser -> {
            List<SmtDev> smtDev = weixinHelloApi.queryDev(yxUser.getUid());
            if (!CollectionUtils.isEmpty(smtDev)){
                yxUser.setSmtDevList(smtDev);
            }
        });
        return Result.OK(pageList);
    }

    /**
     * @param yxUser
     */
    @PostMapping(value = "/addIntegral")
    public void addIntegral(@RequestBody YxUser yxUser) {
        YxUser user = yxUserService.getById(yxUser.getUid());
        user.setIntegral(yxUser.getIntegral() == null ? user.getIntegral() : yxUser.getIntegral().add(user.getIntegral()));
        yxUserService.updateById(user);
    }
    /**
     * @param yxUser
     */
    @PostMapping(value = "/subIntegral")
    public void subIntegral(@RequestBody YxUser yxUser) {
        YxUser user = yxUserService.getById(yxUser.getUid());
        user.setIntegral(yxUser.getIntegral() == null ? user.getIntegral() : user.getIntegral().subtract(yxUser.getIntegral()));
       yxUserService.updateById(user);
    }


    /**
     * 商家端小程序员工绑定店铺
     */
    @PostMapping(value = "/bindMerchant")
    public Result<?> bindMerchant(@RequestBody YxUser yxUser) {
        if (yxUser.getUserIds().size() == 0) {
            return Result.error(606, "暂未选择用户!");
        }
        yxUser.getUserIds().stream().forEach(user -> {
            user.setMerchantId(Integer.valueOf(yxUser.getMerId()));
            yxUserService.updateById(user);
            LoginUser loginUser = new LoginUser();
            loginUser.setMerchantId(Integer.valueOf(yxUser.getMerId()));
            loginUser.setMerchantName(yxUser.getMerName());
            loginUser.setUsername(user.getPhone());
            loginUser.setPassword("123456");
            loginUser.setRealname(user.getNickname());
//            loginUser.setAdtype(1);
            //保存用户信息至sys_user
            sysBaseAPI.saveUser(loginUser);
            weixinHelloApi.updateDev(user.getUid(),yxUser.getMerId());

        });
        return Result.OK("绑定成功！");
    }


    /**
     * 查询用户工号是否存在
     */
    @PostMapping(value = "/queryWork")
    public Result<?> queryWork(@RequestBody WorkDto workDto ){
        Boolean aBoolean = sysBaseAPI.queryWorkNo(workDto.getWorkNo());
        if (aBoolean.equals(Boolean.FALSE)){
            return Result.error(606,"该用户的工号已存在请重新输入！");
        }
        return Result.ok();
    }

}
